package com.haiyou.dc.es.bi.impl;

import com.github.pagehelper.PageInfo;
import com.haiyou.dc.es.constant.EsConstant;
import com.haiyou.dc.es.entity.form.SearchNovelForm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHits;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author pc
 */
@Service
@Slf4j
public class EsBookNovelService extends EsSearchServiceImpl {

    @Override
    protected String getIndexName() {
        return EsConstant.BOOK_INDEX_NAME;
    }

    @Override
    protected String getTypeName() {
        return EsConstant.BOOK_TYPE_NAME;
    }

    public PageInfo searchBookNovel(SearchNovelForm form) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotEmpty(form.getAuthor())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("author", form.getAuthor()));
        }
        if (StringUtils.isNotEmpty(form.getTitle())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("title", form.getTitle()));
        }
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("wordCount").from(form.getGtWordCount());
        if (form.getLtWordCount() != null && form.getLtWordCount() > 0) {
            rangeQuery.to(form.getLtWordCount());
        }
        boolQueryBuilder.filter(rangeQuery);

        SearchRequestBuilder searchRequestBuilder = this.esClient.prepareSearch(getIndexName())
                .setTypes(getTypeName())
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(boolQueryBuilder)
                .setFrom(form.getPageNum() - 1)
                .setSize(form.getPageSize());
        log.info("------------------------>searchRequestBuilder={}", searchRequestBuilder);

        SearchResponse searchResponse = searchRequestBuilder.get();
        SearchHits searchHits = searchResponse.getHits();
        PageInfo pageInfo = new PageInfo<>();
        pageInfo.setTotal(searchHits.totalHits);
        pageInfo.setPageNum(form.getPageNum());
        pageInfo.setPageSize(form.getPageSize());
        List<Map<String, Object>> list = new ArrayList<>();
        searchHits.forEach(x -> {
            Map<String, Object> source = x.getSource();
            list.add(source);
        });
        pageInfo.setList(list);
        return pageInfo;
    }
}
